package com.wonghiu.framework.transport.netty.client;

import com.wonghiu.framework.cluster.directory.ConsumerDirectory;
//import com.wonghiu.framework.cluster.directory.imp.ChannelDirectory;
import com.wonghiu.framework.cluster.directory.imp.ServiceDirectory;
import com.wonghiu.framework.common.enums.CompressTypeEnum;
import com.wonghiu.framework.common.enums.SerializationTypeEnum;
import com.wonghiu.framework.common.factory.SingletonFactory;
import com.wonghiu.framework.exchange.*;
import com.wonghiu.framework.transport.HRpcRequestTransport;
import com.wonghiu.framework.transport.netty.codec.HRpcMessageEncoder;
import com.wonghiu.framework.common.constants.HRpcTransportConstants;
import com.wonghiu.framework.transport.netty.codec.HRpcMessageDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @Author wonghiu
 * @Date 2021/8/10 21:09
 * @Version 1.0.1
 */
@Slf4j
public final class NettyRpcClient implements HRpcRequestTransport {

    private final ServiceDirectory serviceDirectory;
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;
    private final Map<String, Channel[]> channelsMap;
    private final Random random = new Random();
    private final int CHANNEL_LEN = 2;

    public NettyRpcClient() {
        // initialize resources such as EventLoopGroup, Bootstrap
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                //  The timeout period of the connection.
                //  If this time is exceeded or the connection cannot be established, the connection fails.
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        // If no data is sent to the server within 15 seconds, a heartbeat request is sent
                        p.addLast(new IdleStateHandler(0, 5, 0, TimeUnit.SECONDS));
                        p.addLast(new HRpcMessageEncoder());
                        p.addLast(new HRpcMessageDecoder());
                        p.addLast(new NettyRpcClientHandler());
                    }
                });
//        this.serviceDiscovery = ExtensionLoader.getExtensionLoader(ServiceDiscovery.class).getExtension("zk");
//        this.channelProvider = SingletonFactory.getInstance(ChannelDirectory.class);
        channelsMap = new ConcurrentHashMap<>();
        this.serviceDirectory = SingletonFactory.getInstance(ServiceDirectory.class);

    }

    /**
     * connect server and get the channel ,so that you can send rpc message to server
     *
     * @param inetSocketAddress server address
     * @return the channel
     */
    @SneakyThrows
    public Channel doConnect(InetSocketAddress inetSocketAddress) {
        CompletableFuture<Channel> completableFuture = new CompletableFuture<>();
        bootstrap.connect(inetSocketAddress).addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                log.info("The client has connected [{}] successful!", inetSocketAddress.toString());
                completableFuture.complete(future.channel());
            } else {
                throw new IllegalStateException();
            }
        });
        return completableFuture.get();
    }

    @Override
    public Object sendRpcRequest(HRpcRequest rpcRequest) {
        // build return value
        HRpcCompletableFuture<HRpcResponse<Object>> resultFuture = new HRpcCompletableFuture<>();
        // get server address
        InetSocketAddress inetSocketAddress = serviceDirectory.lookupService(rpcRequest);
//        InetSocketAddress inetSocketAddress = new InetSocketAddress("192.168.56.1", 9991);
        // get  server address related channel
        Channel channel = getChannel(inetSocketAddress);
        if (channel.isActive()) {

            HRpcMessage rpcMessage = HRpcMessage.builder().data(rpcRequest)
                    .codec(SerializationTypeEnum.PROTOSTUFF.getCode())
                    .compress(CompressTypeEnum.GZIP.getCode())
                    .messageType(HRpcTransportConstants.REQUEST_TYPE).build();

            // put unprocessed request
            resultFuture.setStartTimestamp(System.currentTimeMillis());
            HRpcCompletableFuture.put(rpcRequest.getRequestId(), resultFuture);
            channel.writeAndFlush(rpcMessage).addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("client send message: [{}]", rpcMessage);
                } else {
                    future.channel().close();
                    resultFuture.completeExceptionally(future.cause());
                    log.error("Send failed:", future.cause());
                }
            });
        } else {
            throw new IllegalStateException();
        }

        return resultFuture;
    }

    public Channel getChannel(InetSocketAddress inetSocketAddress) {
        int randomIndex = random.nextInt(CHANNEL_LEN);
        while (true) {
            Channel[] channels = channelsMap.get(inetSocketAddress.toString());
            if (channels != null) {
                Channel channel = channels[randomIndex];
                if (channel != null) {
                    return channel;
                } else {
                    channel = doConnect(inetSocketAddress);
                    channels[randomIndex] = channel;
                    return channel;
                }
            } else {
                Channel channel = doConnect(inetSocketAddress);
                channels = new Channel[CHANNEL_LEN];
                channels[randomIndex] = channel;
                // 线程安全
                channelsMap.putIfAbsent(inetSocketAddress.toString(), channels);
            }
        }
    }

    public void close() {
        eventLoopGroup.shutdownGracefully();
    }
}